package com.example.demo.ddd;


import com.example.demo.bean.User;
import com.example.demo.db.UserDB;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * Created by df on 2018/10/8.
 * 拦截器，如果return null 正常访问各个微服务的接口
 * 如果被拦截器拦截将会返回处理的信息，也将不会访问日志记录
 */
public class PreZuulFilter extends ZuulFilter {
    private static final Logger log = LoggerFactory.getLogger(ZuulFilter.class);
    @Bean
    private RedisUtil redisUtil(){
        return new RedisUtil();
    }



    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserDB userDB;


    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String AuthToken =request.getHeader("token");
        String AuthUserAccoun=  request.getHeader("account");
        String tokenMsg=   (String)redisUtil.get(AuthToken);
        System.out.println(tokenMsg+":"+AuthUserAccoun);
        //没有加认证token 就没有访问权限
        //这里可以写具体逻辑(由于数据结构不同未贴出mysql中的数据对比(由username判断token是否过期))
        if(AuthToken =="" || AuthToken ==null||AuthUserAccoun==null||AuthUserAccoun==""){
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"code\":401,\"msg\":\"没有访问权限！\"}");
            ctx.getResponse().setContentType("text/html;charset=UTF-8");
        }else if(tokenMsg==null|| !AuthUserAccoun.equals(tokenMsg)){
             ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"code\":401,\"msg\":\"令牌错误！\"}");
            ctx.getResponse().setContentType("text/html;charset=UTF-8");
        }else if(!AuthToken.equals(userDB.getUserTokenByAccount(AuthUserAccoun))){
            System
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"code\":401,\"msg\":\"令牌过期！\"}");
            ctx.getResponse().setContentType("text/html;charset=UTF-8");
        }

        return null;
    }
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String url = request.getRequestURL().toString();
        //此处判断是否要拦截(登录获取token放开)

        if(url.contains("/login")){
            return false;
        }

        return true;
    }
}
